//选择农药产品登记证号
layui.use(['form', 'layer', 'laydate', 'table', 'laypage'], function () {
    let form = layui.form;
    let layer = layui.layer;
    let laydate = layui.laydate;
    let table = layui.table;
    let laypage = layui.laypage;

    let sql = "select i.*  from  t_trace_upload_record i where i.enterprise_code = ? order by report_time desc";
    //layui 表格data
    let tableDataArr = [];
    let pageQuerycfg = {
        sql: sql,
        data: [window.top.companyinfo.c_id],
        page: {},
        success: function (res) {
            tableDataArr = [];
            res.rows.map(function (item) {
                tableDataArr.push(item);
            });
            //方法级渲染
            table.render({
                elem: '#LAY_table_user',
                //url: 'http://127.0.0.1/yj/upreportQuery',
                //url: upreportUrl,
                data: tableDataArr,
                toolbar: '#barDemo',
                defaultToolbar: [],
                cols: [
                    [{
                            fixed: true,
                            width: 50,
                            templet: function (d) {
                                return (d.LAY_TABLE_INDEX + 1) + (curr - 1) * size;
                            }
                        }, {
                            checkbox: true,
                            fixed: true,
                        }, {
                            field: 'req_id',
                            title: '查询ID',
                            fixed: true
                        }, {
                            field: 'report_type',
                            title: '上报类型',
                            fixed: true
                        }, {
                            field: 'report_time',
                            title: '上报时间',
                            fixed: true,
                            templet: function (d) {
                                return new Date(d.report_time).format('yyyy-MM-dd hh:mm:ss');
                            }
                        }, {
                            field: 'report_code_num',
                            width: 130,
                            title: '上报条数',
                            fixed: true,
                        }, {
                            field: 'process_status',
                            title: '处理状态',
                            fixed: true,
                            width: 130,
                            templet: function (d) {
                                if (d.process_status == 0) {
                                    //return '<a href="#" class="layui-btn layui-btn-xs" class="aqua-color" onclick="uploadInterfaceQuery(\'' + d.req_id + '\', this)">查询</a>';
                                    return "等待处理";
                                } else if (d.process_status == 1) {
                                    return "处理成功";
                                } else {
                                    return "处理失败";
                                }
                            }
                        },
                        {
                            field: 'process_res_filepath',
                            title: '处理详情',
                            fixed: true,
                            width: 130,
                            templet: function (d) {
                                if (d.process_res_filepath) {
                                    return '<a href="#" class="aqua-color" onclick="downfile(\'' + d.process_res_filepath + '\')">处理详情</a>';
                                } else {
                                    return '';
                                }
                            }
                        }
                        /* ,
                                                {
                                                    title: '操作',
                                                    fixed: true,
                                                    width: 100,
                                                    toolbar: '#columnBarDemo'
                                                } */
                    ]
                ],
                id: 'testReload',
                skin: 'line',
                even: true,
                page: false,
                height: 'full-140',
                limit: size,
                limits: [10, 20, 30, 50]

            });

        },
        fail: function (err) {
            console.error(err);
        }

    };
    let countSql = "select count(*) count from t_trace_upload_record where enterprise_code = ?";
    //页面初始化加载分页条和表格数据
    pageQuery(laypage, countSql, [window.top.companyinfo.c_id], pageQuerycfg);

    //执行一个laydate实例
    laydate.render({
        elem: '#reportTime' //指定元素
    });
    //执行一个laydate实例
    laydate.render({
        elem: '#endDate' //指定元素
    });

    //监听头部工具栏事件
    table.on('toolbar(table)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        if ("processStatusQuery" == obj.event) {
            let data = checkStatus.data;
            if (data.length < 1) {
                layer.alert("请选中一行！");
                return;
            }
            let index1 = layer.msg("<div class='tip-content'>上报接口查询中,请等待...</div>", {
                icon: 16,
                time: 0,
                shade: 0.3
            });
            let promiseArr = [];
            let waitHandler = 0; //等待处理个数
            let hasHander = 0; //已经处理过的完成个数
            let completeHander = 0; //处理完成个数
            let errorHander = 0; //同步过程出错个数
            let allPromiseAfterTip = {
                waitHandler: waitHandler,
                hasHander: hasHander,
                completeHander: completeHander,
                errorHander: errorHander
            }
            for (let i = 0; i < data.length; i++) {
                let item = data[i];
                //如果有处理结果则不再查询
                if (item.process_res_filepath && item.process_status != 0) {
                    allPromiseAfterTip.hasHander++;
                    continue;
                }
                //获取选中行dom对象
                let checkedTr = null;
                let tableTr = $('div[lay-id="' + obj.config.id + '"] .layui-table-body').last().find('table tr');
                for (let i = 0; i < tableTr.length; i++) {
                    if (item.LAY_TABLE_INDEX == i) {
                        checkedTr = tableTr.eq(i);
                        break;
                    }
                }
                let toolObj = {
                    isToolbar: true,
                    req_id: item.req_id,
                    tr: checkedTr
                };
                promiseArr.push(queryPromise(toolObj, allPromiseAfterTip));
            }
            Q.all(promiseArr).then(arrs => {
                arrs.forEach(function (data) {
                    queryDone(data, allPromiseAfterTip);
                });
                //多窗口模式，层叠置顶
                layer.open({
                    type: 1,
                    title: '提示',
                    content: '<div class="tip-content">共' + data.length + '个上报记录进行同步<br/>' +
                        '已经完成同步的记录个数：' + allPromiseAfterTip.hasHander + '<br/>' +
                        '同步后，处理状态为【等待处理】的记录个数：' + allPromiseAfterTip.waitHandler + '<br/>' +
                        '同步后，处理状态为【处理成功】或【处理失败】的记录个数：' + allPromiseAfterTip.completeHander + '<br/>' +
                        '同步过程中出现错误的记录个数：' + (allPromiseAfterTip.errorHander ? '' + allPromiseAfterTip.errorHander + '（记录未上传至服务器或服务器返回文件下载失败！）</div>' : allPromiseAfterTip.errorHander),
                    zIndex: layer.zIndex, //重点1
                    shade: 0.3,
                    closeBtn: 1,
                    btn: ['确定'], //可以无限个按钮
                    yes: function (index, layero) {
                        layer.close(index);
                    },
                    success: function (layero) {
                        layer.close(index1);
                        layer.setTop(layero); //重点2
                    }
                });
            }).catch(e => {
                e.index = index1;
                queryFail(e);
            })
            //db.pageBysql(pageQuerycfg);
        }
    });

    //监听行操作事件
    table.on('tool(table)', function (obj) {
        uploadInterfaceQuery(obj);
    });

    let $ = layui.$,
        active = {
            reload: function () {
                //查询sql
                let sql = "select i.*  from  t_trace_upload_record i";
                let req_id = $("#reqId").val();
                let report_time = $("#reportTime").val();
                let end_date = $("#endDate").val();
                let process_status = $("#process_status").val();
                //查询数据
                sql += " where  1=1 and enterprise_code = ? ";
                let searchData = [window.top.companyinfo.c_id];
                if (req_id || report_time || end_date || process_status) {
                    if (req_id) {
                        sql += "and i.req_id = ? ";
                        searchData.push(req_id);
                    }
                    if (report_time) {
                        sql += "and i.report_time >= ? ";
                        searchData.push(Date.parse(report_time + " 00:00:00"));
                    }
                    if (end_date) {
                        sql += "and i.report_time <= ? ";
                        searchData.push(Date.parse(end_date + " 23:59:59"));
                    }
                    if (process_status) {
                        sql += "and i.process_status = ? ";
                        searchData.push(process_status);
                    }

                }
                sql += "    order by report_time desc";
                pageQuerycfg.sql = sql;
                pageQuerycfg.data = searchData;
                let countSql = " select count(*) count from (" + sql + ")";
                pageQuery(laypage, countSql, searchData, pageQuerycfg);
            }
        };
    $('.demoTable .layui-btn').on('click', function () {
        let type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

});

function downfile(downloadPath) {
    choseDirectoryAndDownload(downloadPath);
}
//数据处理结果查询接口url
let uploadInterfaceQueryUrl = apiArr[11].trim();

/**
//单行记录同步
function uploadInterfaceQuery(rowObj) {
    layer.msg("<div class='tip-content'>上报接口查询中,请等待...</div>", {
        icon: 16,
        time: 0,
        success: function (layero, index) {
            commomQuery({
                isToolbar: false,
                req_id: rowObj.data.req_id,
                tr: rowObj.tr
            });
        }
    });

}

/**
 * 同步和批量同共用方法
 */
function queryPromise(toolObj) {
    const defer = Q.defer()
    //发送请求
    $.ajax({
        url: uploadInterfaceQueryUrl,
        data: "reqid=" + toolObj.req_id,
        dataType: 'xml',
        timeout: 6000,
        type: 'POST',
        beforeSend: function (xhr, settings) {
            xhr.setRequestHeader('signature', window.parent.companyinfo.signature);
            xhr.setRequestHeader('version', '1');
        },
        success: function (data) {
            defer.resolve({
                data: data,
                toolObj: toolObj
            });
        },
        error: function (e) {
            defer.reject({
                error: e,
                toolObj: toolObj
            });
        }
    });
    return defer.promise;
}
/**
 * promise done
 * @param {*} data 
 * @param {*} allPromiseAfterTip 
 */
function queryDone(data, allPromiseAfterTip) {
    let data1 = data.data;
    let toolObj = data.toolObj;
    if (!data1) {
        allPromiseAfterTip.errorHander++; //处理失败
        //发生错误则返回等待处理状态
        toolObj.tr.css("background", "pink");
        if (!toolObj.isToolbar) {
            layer.alert(msg);
        }
        return;
    }
    let isSuccess = $(data1).find('RESULT').attr('SUCCESS');
    //如果是正在处理中不进行后续操作
    msg = "等待处理中！";
    if (isSuccess == 0) {
        allPromiseAfterTip.waitHandler++; //等待处理
        if (!toolObj.isToolbar) {
            layer.alert(msg);
        }
        toolObj.tr.css("background", "lightblue");
        return;
    }
    toolObj.tr.css("background", "#a9f1a4");
    //返回的xml文件内容
    let content = data1.documentElement.outerHTML.trim();
    let file = `${window.top.__dirname}/../../../temp/result/` + uuid.v1() + '.xml';
    //修改文件路径，在electron中带\符号路径下载出错
    file = file.replace(/\\/g, '/');
    //将data保存在xml文件后，更新sqlite库
    let promise = Q.nfcall(fs.writeFile, file, content, 'utf8');
    promise.then(() => {
        let sql = "update t_trace_upload_record set process_status = ? , process_res_filepath = ? where req_id = ?";
        let searchDataArr = [isSuccess, file, toolObj.req_id];
        db.updateBysql(sql, searchDataArr, function () {
            if (isSuccess == 1) {
                msg = "处理成功";
            } else {
                msg = "处理失败";
            }
            toolObj.tr.find("td[data-field='process_status'] div").text(msg);
            toolObj.tr.find("td[data-field='process_res_filepath'] div").html('<a href="#" class="aqua-color" onclick="downfile(\'' + file + '\')">处理详情</a>');
            if (!toolObj.isToolbar) {
                layer.alert(msg);
            }
        }, function (error) {
            log.error(error);
        });
    }).catch(e => {
        log.error(err)
    });
    allPromiseAfterTip.completeHander++; //处理完成
}

/**
 * promise fail
 * @param {*} e 
 */
function queryFail(e) {
    log.error(e);
    let toolObj = e.toolObj;
    let index1 = e.index;
    if (!toolObj.isToolbar) {
        layer.alert("服务器请求超时！");
    }
    if (!toolObj.isToolbar) {
        toolObj.tr.css("background", "pink");
    }
    //多窗口模式，层叠置顶
    layer.open({
        type: 1,
        title: '提示',
        content: '<div class="tip-content">同步过程出现错误，服务器响应超时，请联系管理员！</div>',
        zIndex: layer.zIndex, //重点1
        shade: 0.3,
        closeBtn: 1,
        btn: ['确定'], //可以无限个按钮
        yes: function (index, layero) {
            layer.close(index);
        },
        success: function (layero) {
            layer.close(index1);
            layer.setTop(layero); //重点2
        }
    });
}

//当前页条数
let size = null;
//当前页码
let curr = null;
/**
 * 加载分页条和表格数据
 * @param {*} laypage laypage对象
 * @param {*} countSql 计算总数
 * @param {*} searchData 预处理sql参数数组
 * @param {*} pageQuerycfg  pageQuerycfg对象
 */
function pageQuery(laypage, countSql, searchData, pageQuerycfg) {
    db.selectBysql(countSql, searchData,
        function (d) {
            laypage.render({
                elem: 'test1',
                count: d[0].count, //数据总数，从服务端得到
                prev: '<em><</em>',
                next: '<em>></em>',
                layout: ['prev', 'page', 'next', 'limit', 'count', 'skip'],
                limit: 20,
                limits: [10, 20, 30, 50],
                jump: function (obj, first) {
                    //obj包含了当前分页的所有参数，比如：
                    //console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                    //console.log(obj.limit); //得到每页显示的条数
                    size = obj.limit;
                    curr = obj.curr;
                    pageQuerycfg.page.index = obj.curr;
                    pageQuerycfg.page.size = obj.limit;
                    db.pageBysql(pageQuerycfg);

                }
            });
        },
        function (err) {
            log.error(err);
        });

}